import axios from 'axios'
import cookie from 'react-cookies'
import { getTokenTime } from '@/utils/auth.js'
import { createBrowserHistory } from 'history'

const request = axios.create({
  //创建axios实例，在这里可以设置请求的默认配置
  baseURL: 'http://liufusong.top:8888',
})

// 请求拦截器
// if (token) {
//   config.headers.Authorization = 'Bearer ' + token
// } else {
// }

request.interceptors.request.use(config => {
  const token = cookie.load('usertoken')
  const history = createBrowserHistory();
  const timer = Date.now() - getTokenTime()
  if (timer > getTokenTime()) {
    history.push('/login')
    return Promise.reject(new Error('登录失效'))
  }
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
})

// const token = cookie.load('usertoken')
// if (token) {
//   const history = createBrowserHistory();
//   request.interceptors.request.use((config) => {
// const timer = Date.now() - getTokenTime()
// if (timer > getTokenTime()) {
//   history.push('/login')
//   return Promise.reject(new Error('登录失效'))
// }
//     config.headers.Authorization = 'Bearer ' + token
//     return config
//   })
// }

request.interceptors.response.use(
  res => {
    // console.log(res);
    const { status, data, msg, message } = res
    // console.log(data, status);
    if (status >= 200 && status <= 400) {
      return data
    } else {
      console.log(msg || message)
    }
  },
  err => {
    if (err.response && err.response === 401) {
      console.log(err)
    } else {
      console.log(err)
    }
  }
) // 响应拦截器

export default request
